<template>
  <div>
    <div class="w-100 flex" style="height:97.9%">
      <div class="h-100 flex-column justify-between" style="width:25%">
        <div data-bottom class="h-33">
          <!-- <router-link particulars :to="{ name: 'Fourstage', query: { code: '000102', name: 'industrial-base', typeCode: '00010203' } }"> -->
          <page-header text="土地性质情况" :ph="250"> <v-chart v-if="nyzjrs.isShow" ref="tdxzqk" :theme="theme" :options="nyzjrs"/></page-header>
          <!-- </router-link> -->
        </div>
        <div data-bottom class="h-33">
          <page-header text="土地经营情况" :ph="250">
            <v-chart v-if="category2.isShow" ref="tdjyqk" :theme="theme" :options="category2"
          /></page-header>
        </div>
        <div data-bottom class="h-33">
          <!-- <router-link particulars :to="{ name: 'Fourstage', query: { code: '000102', name: 'industrial-base', typeCode: '00010204' } }"> -->
          <page-header text="土地流转情况" :ph="250"> <v-chart v-if="kyjgdata.isShow" ref="tdlzms" :theme="theme" :options="kyjgdata"/></page-header>
          <!-- </router-link> -->
        </div>
      </div>
      <div style="width:1%" />
      <div class="h-100" data-bottom style="width:74%;height:100%;padding: 2px;">
        <div id="container" style="height: 100%" />
        <div class="map-legend">
          <div v-for="item in colorList" :key="item.color" class="flex map-legend-item">
            <div class="map-legend-color" :style="{ background: item.color }" />
            <div class="">{{ item.type }}</div>
          </div>
        </div>
      </div>
    </div>
    <div style="height:2.1%" />
    <Particulars />
  </div>
</template>

<script>
import AMap from '@/utils/AMap'
import Particulars from 'header/particulars.vue'
import PageHeader from 'header/PageHeader.vue'
import { Promise } from 'jszip/lib/external'
import theme from '@/utils/echarts-theme.json'
import { formatNumber } from '@/utils/app'
import { getSingleValue, getTowSideStat, landInfo } from '@/api/connector'
import { createInfoWindow } from '@/utils/app'
const tooltip = function(a, b) {
  return {
    trigger: 'axis',
    axisPointer: {
      type: 'shadow'
    },
    // formatter: '{b}<br />{a2}:{c2}%<br />{a1}:{c1}%<br />{a0}:{c0}%'
    formatter: function(params, ticket, callback) {
      var htmlStr = ''
      for (var i = 0; i < params.length; i++) {
        var param = params[i]
        var xName = param.name // x轴的名称
        var seriesName = param.seriesName // 图例名称
        var value = param.value // y轴值
        var color = param.color // 图例颜色
        if (i === 0) {
          htmlStr += xName + '<br/>' // x轴的名称
        }
        htmlStr += '<div>'
        htmlStr +=
          '<span style="margin-right:5px;display:inline-block;width:10px;height:10px;border-radius:5px;background-color:' + color + ';"></span>' //一个点
        htmlStr += seriesName + '：' + value + (i === 0 ? a : b) // 圆点后面显示的文本
        htmlStr += '</div>'
      }
      return htmlStr
    }
  }
}
export default {
  name: 'IndustrialBase',
  components: {
    // eslint-disable-next-line vue/no-unused-components
    PageHeader,
    Particulars
  },
  data() {
    return {
      map: null,
      amap: '',
      infoWindow: null,
      p1: null,
      p2: null,
      theme: theme,
      showIndex: 0,
      mapData: [],
      time: null,
      starCenter: [108.19848536074164, 34.241771035259845],
      colorList: [
        {
          type: '农用地',
          color: '#2DAFFF'
        },
        {
          type: '建设用地',
          color: '#6141FF'
        }
      ],
      kyjgdata: {
        isShow: false,
        tooltip: tooltip('万亩', '万元'),
        legend: {
          textStyle: {
            color: '#fff'
          },
          data: ['最新成交价', '预购队列']
        },
        xAxis: {
          type: 'category',
          data: ['2019', '2018'],
          axisLine: {
            lineStyle: {
              color: '#E9F7FF',
              width: 1
            }
          }
        },
        yAxis: [
          {
            name: '万亩',
            position: 'right',
            nameTextStyle: {
              align: 'left'
            },
            axisLine: {
              lineStyle: {
                color: '#E9F7FF',
                width: 1
              }
            }
          },
          {
            name: '万元',
            position: 'left',
            nameTextStyle: {
              align: 'left'
            },
            axisLine: {
              lineStyle: {
                color: '#E9F7FF',
                width: 1
              }
            }
          }
        ],
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        series: [
          {
            name: '平均流转价格',
            type: 'bar',
            barMaxWidth: 30,
            xAxisIndex: 1,
            yAxisIndex: 1,
            data: [6, 7, 8, 16]
          },
          {
            name: '土地流转亩数',
            type: 'line',
            data: [6, 7, 8, 15, 25]
          }
        ]
      },
      category2: {
        isShow: false,
        tooltip: {
          trigger: 'axis',

          formatter: '{a} <br/>{b}年: {c}万亩',
          axisPointer: {
            type: 'cross',
            label: {
              backgroundColor: '#6a7985'
            }
          }
        },
        legend: {
          data: ['邮件营销', '联盟广告', '视频广告', '直接访问', '搜索引擎']
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: [
          {
            type: 'category',
            boundaryGap: false,
            data: ['周一', '周二', '周三', '周四', '周五', '周六', '周日']
          }
        ],
        yAxis: [
          {
            name: '万亩',
            type: 'value'
          }
        ],
        series: [
          {
            name: '邮件营销',
            type: 'line',
            stack: '总量',
            areaStyle: {},
            data: [120, 132, 101, 134, 90, 230, 210]
          },
          {
            name: '联盟广告',
            type: 'line',
            stack: '总量',
            areaStyle: {},
            data: [220, 182, 191, 234, 290, 330, 310]
          },
          {
            name: '视频广告',
            type: 'line',
            stack: '总量',
            areaStyle: {},
            data: [150, 232, 201, 154, 190, 330, 410]
          }
        ]
      },
      nyzjrs: {
        isShow: false,
        // title: {
        //   text: '',
        //   x: 'center',
        //   y: 'center',
        //   textStyle: {
        //     fontSize: 14
        //   }
        // },
        title:[
          {
            text: '',
            left: 'center',
            top: '40%',
            textStyle: {
              color: '#fff',
              fontSize: 14
            }
          },
          {
            id: 'statistic',
            text: "万亩",
            left: 'center',
            top: '50%',
            textStyle: {
              color: '#fff',
              fontSize: 14
            }
          }
        ],
        tooltip: {
          trigger: 'item',
          formatter: '{a} <br/>{b}: {c}万亩 ({d}%)'
        },
        legend: {
          orient: 'vertical',
          left: 10,
          data: []
        },
        series: [
          {
            name: '',
            type: 'pie',
            radius: ['50%', '70%'],
            avoidLabelOverlap: false,
            emphasis: {
              label: {
                show: true
                // fontSize: '30',
                // fontWeight: 'bold'
              }
            },
            label: {
              show: true,
              position: 'bottom',
              offset: [0, 50],
              formatter: function(params) {
                // if (params.name !== '') {
                //   // return params.name + '\n' + '(' + params.percent + '%)';
                //   return params.value + ' 万亩'
                // } else {
                //   return ''
                // }

                return params.percent + '%'
              }
            },
            labelLine: {
              show: true
            },
            data: [
              { value: 335, name: '直接访问' },
              { value: 310, name: '邮件营销' },
              { value: 234, name: '联盟广告' },
              { value: 135, name: '视频广告' },
              { value: 1548, name: '搜索引擎' }
            ]
          }
        ]
      }
    }
  },
  mounted() {
    this.initTick()
  },
  created() {
    this.init()
  },
  beforeDestroy() {
    clearTimeout(this.time)
  },
  methods: {
    initTick() {
      this.$nextTick(() => {
        this.initAMap()

        this.drawPolygon()
      })
    },
    init() {
      // 土地性质情况
      getSingleValue({
        groupCode: 'TDXZQK'
      }).then((res) => {
        this.nyzjrs.legend.data = res.body.names
        this.nyzjrs.series[0].data = []
        // eslint-disable-next-line no-undef
        var i = 0
        var series = []
        for (i = 0; i < res.body.names.length; i++) {
          var item = {
            name: res.body.names[i],
            value: res.body.values[i]
          }
          series.push(item)
        }
        let num = 0
        series.map((item) => {
          num = num + item.value
        })
        this.nyzjrs.title[0].text = formatNumber(num)
        this.nyzjrs.series[0].data = series
        this.nyzjrs.isShow = true
        this.toLink(this, 'tdxzqk', (params) => {
          if (params.data.name == '耕地面积') {
            this.$router.push({ name: 'Fourstage', query: { code: '000102', typeCode: '耕地面积总数', name: 'industrial-base' } })
          }
        })
      })
      //  土地经营情况
      getTowSideStat({ groupCode: 'TDJYQK' }).then((res) => {
        // console.log(res.body)
        this.category2.xAxis[0].data = res.body.dateSet
        this.category2.legend.data = res.body.typeSet
        var obj = res.body.typeValueListMap
        var key = []
        var value = []
        for (var i in obj) {
          key.push(i)
          value.push(obj[i])
        }
        this.category2.series[0].data = value[0]
        this.category2.series[0].name = key[0]
        this.category2.series[1].data = value[1]
        this.category2.series[1].name = key[1]
        this.category2.series[2].data = value[2]
        this.category2.series[2].name = key[2]
        this.category2.isShow = true
        this.toLink(this, 'tdjyqk', (params) => {
          this.$router.push({ name: 'Fourstage', query: { code: '000102', typeCode: '主要农产品种植面积', name: 'industrial-base' } })
        })
      })
      // 土地流转情况
      getTowSideStat({ groupCode: 'TDLZQK' }).then((res) => {
        const val = res.body
        const kyjgdata = this.kyjgdata
        kyjgdata.xAxis.data = val.dateSet
        kyjgdata.legend.data = val.typeSet
        // kyjgdata.series[0].data = val.typeValueListMap[kyjgdata.series[0].name]
        // kyjgdata.series[1].data = val.typeValueListMap[kyjgdata.series[1].name]

        var typeValueListMap = res.body.typeValueListMap
        var valArrKey = []
        var valArrval = []
        for (var key in typeValueListMap) {
          valArrKey.push(key)
          valArrval.push(typeValueListMap[key])
        }
        this.kyjgdata.series = valArrval.map((item, index) => {
          return {
            name: valArrKey[index],
            data: valArrval[index],
            type: index === 0 ? 'bar' : 'line',
            yAxisIndex: index
          }
        })
        this.kyjgdata.isShow = true
        this.toLink(this, 'tdlzms', (params) => {
          this.$router.push({ name: 'Fourstage', query: { code: '000102', typeCode: '土地流转亩数', name: 'industrial-base' } })
        })
      })
    },
    async initAMap() {
      try {
        const self = this
        this.amap = await AMap()
        var opts = {
          subdistrict: 0,
          extensions: 'all',
          level: 'city'
        }

        var district = new self.amap.DistrictSearch(opts)
        district.search('咸阳市', function(status, result) {
          var bounds = result.districtList[0].boundaries
          var mask = []
          for (var i = 0; i < bounds.length; i += 1) {
            mask.push([bounds[i]])
          }
          self.map = new self.amap.Map('container', {
            mask: mask,
            center: [108.19848536074164, 34.241771035259845],
            disableSocket: true,
            viewMode: '3D',
            showLabel: false,
            labelzIndex: 130, // 地图标注显示顺序，大于110即可将底图上的默认标注显示在覆盖物（圆、折线、面）之上。
            pitch: 40, // 俯仰角度，默认0，[0,83]，2D地图下无效 。（自V1.4.0开始支持）
            zoom: 16,
            layers: [
              new self.amap.TileLayer.RoadNet({
                // rejectMapMask:true
              }),
              new self.amap.TileLayer.Satellite()
            ]
          })
          // 添加自定义图层
          self.map.plugin(['AMap.CustomLayer'], function() {
            var size = self.map.getSize()
            var canvas = document.createElementNS('http://www.w3.org/2000/svg', 'svg')
            canvas.setAttribute('xmlns', 'http://www.w3.org/2000/svg')
            canvas.setAttribute('width', size.width)
            canvas.setAttribute('height', size.height)

            self.path = document.createElementNS('http://www.w3.org/2000/svg', 'path')
            self.path.onclick = function() {
              // console.log('svg path clicked')
            }
            var styleText = []
            styleText.push('stroke:#132235')
            styleText.push('fill:#132235')
            styleText.push('fill-opacity:0.6')
            self.path.style.cssText = styleText.join(';')

            canvas.appendChild(self.path)
            var customLayer = new self.amap.CustomLayer(canvas, {
              // zooms: [3, 8],
              alwaysRender: true,
              zIndex: 100
            })
            customLayer.render = self.onRender
            self.map.add(customLayer)
          })

          // 添加高度面
          var object3Dlayer = new self.amap.Object3DLayer({ zIndex: 1 })
          self.map.add(object3Dlayer)
          var height = -8000
          var color = '#0088ffcc' // rgba
          var wall = new self.amap.Object3D.Wall({
            path: bounds,
            height: height,
            color: color
          })
          wall.transparent = true
          object3Dlayer.add(wall)

          // 添加描边
          for (let i = 0; i < bounds.length; i += 1) {
            new self.amap.Polyline({
              path: bounds[i],
              strokeColor: '#99ffff',
              strokeWeight: 4,
              map: self.map
            })
          }
          self.landInfo()
        })
      } catch (err) {
        console.error(err)
      }
    },
    buildPath() {
      var path = []
      var center = this.map.lngLatToContainer(this.starCenter)
      for (let k = 0; k < 6; k += 1) {
        var ag = ((Math.PI * 60) / 180) * k
        var x = center.x + Math.cos(ag) * 500000
        var y = center.y + Math.sin(ag) * 500000
        path.push((k === 0 ? 'M' : 'L') + x + ' ' + y)
      }
      return path.join(' ') + ' Z'
    },
    onRender() {
      var newPath = this.buildPath()
      this.path.setAttribute('d', newPath)
    },
    addPolygon(data) {
      const self = this
      const markers = []
      data.forEach((item, index) => {
        const b = []
        const f = JSON.parse(item.coordinate)
        f.map((ite) => {
          b.push(new this.amap.LngLat(ite.lng, ite.lat))
        })
        let color = ''
        this.colorList.map((d) => {
          if (d.type === item.landUse) {
            color = d.color
          }
        })
        const polygon = new this.amap.Polygon({
          title: item.name,
          data: item,
          path: b,
          strokeColor: color, // 线颜色
          strokeOpacity: 0.2, // 线透明度
          strokeWeight: 10, // 线宽
          fillColor: color, // 填充色
          fillOpacity: 0.8 // 填充透明度
        })
        polygon.on('click', function(e) {
          self.openInfo(e, item)
        })
        self.mapData.push({
          position: [f[0].lng, f[0].lat],
          data: item
        })
        markers.push(polygon)
      })
      const overlayGroups = new this.amap.OverlayGroup(markers)
      this.map.add(overlayGroups)
      self.setMapCenter()
    },
    setMapCenter() {
      const self = this
      this.time = setTimeout(() => {
        self.map.setCenter(self.mapData[self.showIndex].position)
        const lnglat = self.mapData[self.showIndex].position
        self.openInfo({ lnglat }, self.mapData[self.showIndex].data)
        if (self.showIndex === self.mapData.length - 1) {
          self.showIndex = 0
        } else {
          self.showIndex++
        }
        self.setMapCenter()
      }, 8000)
    },
    openInfo(e, data) {
      const self = this
      const title = '地块详情'
      const content = []
      content.push('<div class="flex"><div class="w-105">地块编码:</div><div>' + data.code + '</div></div>')
      content.push('<div class="flex"><div class="w-105">合同亩数:</div><div>' + data.contractPerMu + '</div></div>')
      content.push('<div class="flex"><div class="w-105">实测亩数:</div><div>' + data.realityPerMu + '</div></div>')
      content.push('<div class="flex"><div class="w-105">所有权性质:</div><div>' + data.ownershipNature + '</div></div>')
      content.push('<div class="flex"><div class="w-105">土地用途:</div><div>' + data.landUse + '</div></div>')
      content.push('<div class="flex"><div class="w-105">承包方式:</div><div>' + data.contractMode + '</div></div>')
      content.push('<div class="flex"><div class="w-105">发包方全称:</div><div>' + data.employer + '</div></div>')
      content.push('<div class="flex"><div class="w-105">法人代表:</div><div>' + data.legalRepresentative + '</div></div>')
      content.push('<div class="flex"><div class="w-105">承包方姓名:</div><div>' + data.contractorName + '</div></div>')
      content.push('<div class="flex"><div class="w-105">共有人数:</div><div>' + data.numer + '</div></div>')
      content.push('<div class="flex"><div class="w-105">权证编号:</div><div>' + data.warrantNo + '</div></div>')
      content.push('<div class="flex"><div class="w-105">合同编号:</div><div>' + data.contractNo + '</div></div>')
      content.push('<div class="flex"><div class="w-105">经营取得方式:</div><div>' + data.businessMode + '</div></div>')
      content.push('<div class="flex"><div class="w-105">承包土地用途:</div><div>' + data.contractedLandUse + '</div></div>')
      this.infoWindow = new this.amap.InfoWindow({
        isCustom: true, // 使用自定义窗体
        content: createInfoWindow(title, content.join('<br/>'), self.map, 0),
        offset: new this.amap.Pixel(16, -45)
      })
      this.infoWindow.open(this.map, e.lnglat)
    },
    landInfo(item) {
      this.p2 = new Promise((resolve, reject) => {
        landInfo().then((res) => {
          this.addPolygon(res.body.data)
        })
      })
    }
  }
}
</script>
<style lang="scss" scoped>
.w-105 {
  width: 105px;
}
.h-33 {
  height: 32%;
}
div[data-bottom] {
  background: url(~@/assets/img/gradients-right.png) no-repeat;
  background-size: 100% 100% !important;
}
.h-24 {
  height: 23.2%;
}

.test {
  z-index: 1000;
  position: fixed;
  top: 300px;
  left: 300px;
  background: #fff;
}

.w-30 {
  width: 30%;
}

.map-legend {
  padding: 12px 18px;
  position: fixed;
  left: 27.5%;
  bottom: 3.5%;
  z-index: 1000;
  color: #fff;
  background: rgba(18, 33, 53, 0.8);
  border-radius: 4px;
}
.map-legend-color {
  width: 40px;
  height: 18px;
  margin-right: 10px;
}
.map-legend-item {
  margin-bottom: 8px;
}
.map-legend-item:last-child {
  margin-bottom: 0;
}
</style>
